from . import settings

from sqlalchemy     import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session

# The SQLAlchemy "Engine" is the "starting point" for using SQLAlchemy. In this
# plugin we do not reuse the Pagure database session, because we're using a
# separate database (we do not create new tables in the Pagure database in
# order to keep the plugin completely separate). A new session for querying the
# database is started at the beginning of every incoming HTTP request, or when
# a Celery task is ran.
# 
# Useful documentation for SQLAlchemy to understand how the plugin is set up:
#     https://docs.sqlalchemy.org/en/13/orm/contextual.html
engine = create_engine(settings.DB_URL, echo=True, pool_recycle=3600)

def start_database_session():
    """
    Get a new SQLAlchemy work session. The Session object is used to query the
    database. To end a session simply call .remove() on the session object that
    is returned from this function.
    
    sessionmaker() is a SQLAlchemy session factory.
    scoped_session() is a SQLAlchemy registry of session objects. By
        using this registry, if somewhere else in the same request were
        to create a new session, the *same* object will be returned instead
        of starting a new one. Sessions are thread-local (2 different flask
        requests will start different sessions).
    """
    
    return scoped_session(sessionmaker(bind=engine))
